from re import I
import sqlite3
from .database_pool import DatabasePool
from peewee import *
from datetime import datetime


# 数据模型定义
class BaseStockInfoModel(Model):
    # 股票代码
    ts_code = CharField(max_length=10, unique=True)
    # 股票简称
    symbol = CharField(max_length=50)
    # 股票名称
    name = CharField(max_length=100)
    # 所在区域
    area = CharField(max_length=50)
    # 行业分类
    industry = CharField(max_length=100)
    # 拼音首字母
    cnspell = CharField(max_length=50)
    # 市场分类
    market = CharField(max_length=50)
    # 上市日期
    list_date = DateField()
    # 行业活动名称
    act_name = CharField(max_length=100)
    # 企业类型
    act_ent_type = CharField(max_length=50)

    class Meta:
        database = DatabasePool(max_connections=5).database  # 指定数据库连接
        table_name = "base_stock_info"  # 指定表名


# 服务类
class StockInfoService:

    # 新增股票信息记录
    def add_stock_info(self, stock_info: dict):
        try:
            BaseStockInfoModel.create(
                ts_code=stock_info['ts_code'],
                symbol=stock_info['symbol'],
                name=stock_info['name'],
                area=stock_info['area'],
                industry=stock_info['industry'],
                cnspell=stock_info['cnspell'],
                market=stock_info['market'],
                list_date=stock_info['list_date'],
                act_name=stock_info['act_name'],
                act_ent_type=stock_info['act_ent_type']
            )
            AntLogger.info("股票信息记录已添加。")
        except ValueError as ve:
            AntLogger.info(f"字段类型转换错误: {ve}")
        except Exception as e:
            AntLogger.info(f"新增记录时出错: {e}")

    # 更新股票信息记录
    def update_stock_info(self, ts_code: str, updated_info: dict):
        try:
            # 根据股票代码查找记录
            stock = BaseStockInfoModel.get(BaseStockInfoModel.ts_code == ts_code)

            # 更新各字段
            if 'symbol' in updated_info:
                stock.symbol = updated_info['symbol']
            if 'name' in updated_info:
                stock.name = updated_info['name']
            if 'area' in updated_info:
                stock.area = updated_info['area']
            if 'industry' in updated_info:
                stock.industry = updated_info['industry']
            if 'cnspell' in updated_info:
                stock.cnspell = updated_info['cnspell']
            if 'market' in updated_info:
                stock.market = updated_info['market']
            if 'list_date' in updated_info:
                stock.list_date = updated_info['list_date']
            if 'act_name' in updated_info:
                stock.act_name = updated_info['act_name']
            if 'act_ent_type' in updated_info:
                stock.act_ent_type = updated_info['act_ent_type']

            # 保存更改
            stock.save()
            AntLogger.info(f"股票信息记录已更新：{ts_code}")
        except DoesNotExist:
            AntLogger.info(f"未找到股票代码为 {ts_code} 的记录。")
        except Exception as e:
            AntLogger.info(f"更新记录时出错: {e}")

    # 删除股票信息记录
    def delete_stock_info(self, ts_code: str):
        try:
            # 查找记录
            stock = BaseStockInfoModel.get(BaseStockInfoModel.ts_code == ts_code)
            # 删除记录
            stock.delete_instance()
            AntLogger.info(f"股票代码 {ts_code} 的信息记录已删除。")
        except DoesNotExist:
            AntLogger.info(f"未找到股票代码为 {ts_code} 的记录。")
        except Exception as e:
            AntLogger.info(f"删除记录时出错: {e}")

    # 获取所有股票信息记录
    def get_all_stock_info(self):
        try:
            records = BaseStockInfoModel.select()
            return list(records)
        except Exception as e:
            AntLogger.info(f"获取股票信息列表时出错: {e}")
            return []

    # 根据股票代码查询单条股票信息记录
    def get_stock_info_by_code(self, ts_code: str):
        try:
            stock_info = BaseStockInfoModel.get(BaseStockInfoModel.ts_code == ts_code)
            return stock_info
        except DoesNotExist:
            AntLogger.info(f"未找到股票代码为 {ts_code} 的记录。")
            return None
        except Exception as e:
            AntLogger.info(f"查询记录时出错: {e}")
            return None
